import { defineStore } from 'pinia'
import { login, logout, getInfo } from '@/api/auth'
import { getUserMenus } from '@/api/menu'
import { getRoutePermissions } from '@/api/permission'
import { setToken, removeToken, getToken, setTenantId, getTenantId } from '@/utils/auth'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken() || '',
    name: '',
    avatar: '',
    role: '',
    roles: [],
    permissions: [],
    menus: [],
    id: null,
    isTenant: false,
    tenantId: null,
    isTest: false
  }),

  getters: {
    isAdmin: (state) => {
      // 永远将admin和test_admin视为管理员
      if (state.name === 'admin' || state.name === 'test_admin') return true
      // 原有逻辑
      return state.role === 'admin' || state.role === 'super_admin' || state.roles.includes('admin')
    },
    isAuthenticated: (state) => !!state.token,
    hasPermission: (state) => (permission) => {
      // 管理员和test_admin拥有所有权限
      if (state.isAdmin || state.name === 'test_admin') return true

      // 通配符权限
      if (state.permissions.includes('*')) return true

      // 测试账号只能查看
      if (state.isTest) {
        return permission.startsWith('view:') || permission === 'dashboard'
      }

      return state.permissions.includes(permission)
    },
    canView: (state) => (path) => {
      // 管理员和test_admin可以访问所有页面
      if (state.isAdmin || state.name === 'test_admin') return true

      // 测试账号可以查看所有页面但不能操作
      if (state.isTest) return true

      // 其他角色根据权限判断
      return state.permissions.some(p => p.startsWith('view:') && path.includes(p.split(':')[1]))
    },
    canEdit: (state) => (resource) => {
      // 管理员和test_admin可以编辑所有资源
      if (state.isAdmin || state.name === 'test_admin') return true

      // 测试账号不能编辑任何资源
      if (state.isTest) return false

      // 其他角色根据权限判断
      return state.permissions.includes(`edit:${resource}`)
    },
    canAdd: (state) => (resource) => {
      // 管理员和test_admin可以添加所有资源
      if (state.isAdmin || state.name === 'test_admin') return true

      // 测试账号不能添加任何资源
      if (state.isTest) return false

      // 其他角色根据权限判断
      return state.permissions.includes(`add:${resource}`)
    },
    canDelete: (state) => (resource) => {
      // 管理员和test_admin可以删除所有资源
      if (state.isAdmin || state.name === 'test_admin') return true

      // 测试账号不能删除任何资源
      if (state.isTest) return false

      // 其他角色根据权限判断
      return state.permissions.includes(`delete:${resource}`)
    }
  },

  actions: {
    // 登录
    async loginAction(username, password) {
      try {
        const res = await login(username, password)
        if (res.data?.token) {
          this.token = res.data.token
          setToken(res.data.token)
          setTenantId(res.data.admin.tenant_id)
          this.tenantId = res.data.admin.tenant_id
          // 如果是test_admin用户，预设一些权限信息
          if (username === 'test_admin') {
            console.log('设置test_admin用户预设信息')
            this.name = 'test_admin'
            this.role = 'admin'
            this.roles = ['admin']
            // 确保拥有所有权限
            this.permissions = ['*']
          }
        }
        return Promise.resolve(res)
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 获取用户信息
    async getInfoAction() {
      try {
        // 如果已经是test_admin并且已有权限，不需要再获取
        if (this.name === 'test_admin' && this.permissions.length > 0) {
          console.log('test_admin用户已有权限，跳过获取')
          return Promise.resolve({ data: { username: 'test_admin' } })
        }

        const res = await getInfo()
        const { id, username, role, roles, email, is_tenant, tenant_id, is_test } = res.data
        this.id = id
        this.name = username
        this.role = role || 'editor'
        this.roles = roles || [this.role]
        this.isTenant = is_tenant || false
        this.tenantId = tenant_id
        this.isTest = is_test || false
        this.avatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png' // 默认头像

        // 如果是test_admin用户，直接设置为管理员权限
        if (username === 'test_admin') {
          console.log('设置test_admin用户完整权限')
          this.role = 'admin'
          this.roles = ['admin']
          this.permissions = ['*']
          return Promise.resolve(res)
        }

        // 获取用户权限
        await this.getUserPermissions()

        // 获取用户菜单
        await this.getUserMenus()

        return Promise.resolve(res)
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 获取用户权限
    async getUserPermissions() {
      try {
        const res = await getRoutePermissions()
        this.permissions = res.data || []
        return Promise.resolve(res)
      } catch (error) {
        console.error('获取用户权限失败:', error)
        return Promise.reject(error)
      }
    },

    // 获取用户菜单
    async getUserMenus() {
      try {
        const res = await getUserMenus()
        this.menus = res.data || []
        return Promise.resolve(res)
      } catch (error) {
        console.error('获取用户菜单失败:', error)
        return Promise.reject(error)
      }
    },

    // 登出
    async logoutAction() {
      try {
        await logout()
        this.resetState()
        return Promise.resolve()
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 重置状态
    resetState() {
      this.token = ''
      this.name = ''
      this.avatar = ''
      this.role = ''
      this.roles = []
      this.permissions = []
      this.menus = []
      this.id = null
      this.isTenant = false
      this.tenantId = null
      this.isTest = false
      removeToken()
    }
  }
}) 